from funasr import AutoModel
from funasr.utils.postprocess_utils import rich_transcription_postprocess
from fastapi import FastAPI
from fastapi import File, UploadFile
import os
import tempfile
import logging
import signal
import sys
import logging.handlers

model_dir = "iic/SenseVoiceSmall"

model = AutoModel(
    model=model_dir,
    vad_model="fsmn-vad",
    vad_kwargs={"max_single_segment_time": 30000},
    device="cuda:0",
    disable_update=True,
)

app = FastAPI()

# 移除原有的basicConfig调用
# 改为手动配置logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# 清除所有现有的handlers
for handler in logger.handlers[:]:
    logger.removeHandler(handler)

# 添加RotatingFileHandler
file_handler = logging.handlers.RotatingFileHandler(
    'app.log', 
    maxBytes=1024*1024, 
    backupCount=5,
    encoding='utf-8'  # 添加编码参数
)
file_handler.setFormatter(logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))

# 添加StreamHandler
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
))

logger.addHandler(file_handler)
logger.addHandler(stream_handler)

# 打印检查信息
print("当前生效的handlers:", logger.handlers)
print("日志文件路径:", os.path.abspath('app.log'))


@app.post("/transcribe")
def transcribe(file: UploadFile = File(...)):
    global model
    with tempfile.NamedTemporaryFile(delete=False) as temp_file:
        temp_file.write(file.file.read())
        temp_file_path = temp_file.name
    try:
        logger = logging.getLogger(__name__)
        logger.info('开始处理文件: %s', temp_file_path)
        res = model.generate(
            input=temp_file_path,
            cache={},
            language='auto',  # 'zn', 'en', 'yue', 'ja', 'ko', 'nospeech'
            use_itn=True,
            batch_size_s=60,
            merge_vad=True,  # 
            merge_length_s=15,
        )
        logger.info('文件处理完成: %s, 转录结果: %s', temp_file_path, res)
        text = rich_transcription_postprocess(res[0]['text'])
        logger.info('文件处理完成: %s, 转录结果: %s', temp_file_path, text)
    except Exception as e:
        logger.error('处理文件 %s 时出错: %s', temp_file_path, str(e))
    finally:
        os.remove(temp_file_path)
    return {'transcription': text}


if __name__ == "__main__":
    logger = logging.getLogger(__name__)
    logger.info('服务启动成功')
    def signal_handler(sig, frame):
        logger.info('接收到Ctrl+C信号，正在停止服务...')
        sys.exit(0)
    signal.signal(signal.SIGINT, signal_handler)
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=8000)